package ext.generic.integration.sourcing.task;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import wt.part.WTPart;
import wt.part.WTPartUsageLink;
import wt.util.WTException;

import com.infoengine.SAK.Task;
import com.infoengine.object.factory.Group;
import com.infoengine.util.IEException;

import ext.com.core.CoreUtil;
import ext.generic.erp.attributes.AttributeUtil;
import ext.generic.erp.common.CommonUtil;
import ext.generic.erp.task.IETaskCommonUtil;
import ext.generic.erp.util.IEXMLUtil;
import ext.generic.integration.sourcing.util.PartAttribute;

public class TwoLevelMaterialBOMTask {
	private static final String RELEASE_QUANTITY = "quantity";
	private static final String RELEASE_FLAG = "flag" ;
	private static final String RELEASE_DATE = "releaseDate" ;
	//二级料编码属性内部名称
	private static final String SECONDARY_MATERIAL_NUMBER = "secondaryMaterialNumber" ;
	private static List<String> processList = new ArrayList<String>();
	
	private static IEXMLUtil ieXMLUtil = new IEXMLUtil();
	//PDM发布数据成功
	public static final String PDM_RELEASE_STATUS = "N" ;
	
	//二级物料BOM结构
	private static String ieXMLFileBOMQuery = "ext/generic/integration/sourcing/bom/BOMQuery.xml" ;
	private static String ieXMLFileBOMCreate = "ext/generic/integration/sourcing/bom/BOMCreate.xml" ;
	private static String ieXMLFileBOMUpdate = "ext/generic/integration/sourcing/bom/BOMUpdate.xml" ;
	private static String ieXMLFileBOMDelete = "ext/generic/integration/sourcing/bom/BOMDelete.xml" ;
	
	static{
		processList.add(RELEASE_QUANTITY);
		processList.add(RELEASE_FLAG);
		processList.add(RELEASE_DATE);
		processList.add(SECONDARY_MATERIAL_NUMBER);
	}
	
	
	public static boolean add( WTPartUsageLink usageLink , String quantity , String releaseTime ) {
		boolean releaseFlag = false;
		if( usageLink == null ){
			return releaseFlag;
		}
		
		if( hasObject( usageLink ) ){
			update( usageLink , quantity , releaseTime );
		}else{
			create( usageLink , quantity , releaseTime );
		}
		releaseFlag = hasObject( usageLink );
		if(releaseFlag){
			System.out.println( usageLink + "二级物料BOM插入中间表成功");
		}else{
			System.out.println( usageLink + "二级物料BOM插入中间表失败");
		}
		return releaseFlag;
	}
	
	/**
	 * 更具指定usageLink从中间表中查询该条数据
	 * @param usageLink
	 * @return
	 */
	public static Group query( WTPartUsageLink usageLink ) {
		Group group = null;
		
		if( usageLink == null ){
			return group;
		}
		
		//创建任务
		Task task = new Task( ieXMLFileBOMQuery );
		
		addQueryWhere( usageLink , task );
		
		try {
			task.invoke();
		} catch (IEException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//获取查询后的返回值
		group = task.getGroup("QueryObjects");
		
		return group;
	}
	
	/**
	 * 删除表中间数据
	 * 
	 * @param usageLink
	 */
	public static void delete( WTPartUsageLink usageLink ){
		
		if( usageLink == null ){
			return;
		}
		
		//创建任务
		Task task = new Task( ieXMLFileBOMDelete );
		
		addQueryWhere( usageLink , task );
		
		try {
			task.invoke();
		} catch (IEException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 向中间表中添加新数据
	 * @param usageLink
	 * @param releaseTime
	 */
	private static void create(WTPartUsageLink usageLink, String quantity , String releaseTime) {
		
		if( usageLink == null ){
			return;
		}
		
		//从IE Task的XML文件中解析属性映射关系
		Map<String,String> fieldMap = ieXMLUtil.parserXml( IETaskCommonUtil.TASK_FILE_DIRECOTRY + ieXMLFileBOMCreate );
		
		Task task = new Task( ieXMLFileBOMCreate );
		
		if( fieldMap != null ){
			Iterator<String> iteratorKey = fieldMap.keySet().iterator();
			
			while( iteratorKey.hasNext() ){
				String key = iteratorKey.next();
				
				if( key != null && ( !key.equals("") ) ){
					String attributeId = fieldMap.get( key );				
					//中间表添加数据为每一列赋值				
					if( processList.contains( attributeId ) ){
						addProcessAttribute(usageLink, attributeId , task , releaseTime , quantity);
					}else{
						String attributeValue = AttributeUtil.getAttribute( usageLink , attributeId );
						System.out.println( "Debug   "+attributeId+":"+attributeValue );
						task.addParam( attributeId , attributeValue );
					}		
				}
			}
		}
		
		try {
			task.invoke();
		} catch (IEException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 单独添加发布状态以及发布时间的值
	 * @param attributeId
	 * @param task
	 * @param releaseTime
	 */
	private static void addProcessAttribute( WTPartUsageLink usageLink, String attributeId , Task task, String releaseTime , String quantity) {

		if( releaseTime == null || ( releaseTime.trim() ).equals("") ){
			releaseTime = CommonUtil.getCurrentTime() ;
		}
		
		if( attributeId.equals( RELEASE_FLAG ) ){
			task.addParam( RELEASE_FLAG, PDM_RELEASE_STATUS );
		}else if( attributeId.equals( RELEASE_DATE ) ){
			task.addParam( RELEASE_DATE , releaseTime );
		}else if( attributeId.equals( RELEASE_QUANTITY ) ){
			task.addParam( RELEASE_QUANTITY, quantity );
		}else if( attributeId.equals( SECONDARY_MATERIAL_NUMBER ) ){
			String secondaryMaterialNumber = getsecondaryMaterialNumber(usageLink);
			task.addParam( SECONDARY_MATERIAL_NUMBER, secondaryMaterialNumber );
		}
	}
	
	private static String getsecondaryMaterialNumber(WTPartUsageLink usageLink) {
		String secondaryMaterialNumber = "";
		try {
			WTPart childPart = CoreUtil.getWTPartByMasterAndView(usageLink.getUses(), usageLink.getUsedBy().getViewName());
			secondaryMaterialNumber = PartAttribute.getAttributeValue(childPart, SECONDARY_MATERIAL_NUMBER);
		} catch (WTException e) {
			e.printStackTrace();
			return secondaryMaterialNumber;
		}
		return secondaryMaterialNumber;
	}

	/**
	 * 更新中间表数据
	 * @param usageLink
	 * @param releaseTime
	 */
	private static void update(WTPartUsageLink usageLink, String quantity , String releaseTime) {
		
		if( usageLink == null ){
			return;
		}
		
		//从IE Task的XML文件中解析属性映射关系
		Map<String,String> fieldMap = ieXMLUtil.parserXml( IETaskCommonUtil.TASK_FILE_DIRECOTRY + ieXMLFileBOMUpdate );
		
		Task task = new Task( ieXMLFileBOMUpdate );
		
		if( fieldMap != null ){
			Iterator<String> iteratorKey = fieldMap.keySet().iterator();
			
			while( iteratorKey.hasNext() ){
				String key = iteratorKey.next();
				
				if( key != null && ( !key.equals("") ) ){
					String attributeId = fieldMap.get( key );				
					//中间表添加数据为每一列赋值				
					if( processList.contains( attributeId ) ){
						addProcessAttribute(usageLink, attributeId , task , releaseTime , quantity );
					}else{
						String attributeValue = AttributeUtil.getAttribute( usageLink , attributeId );
						System.out.println( "Debug   "+attributeId+":"+attributeValue );
						task.addParam( attributeId , attributeValue );
					}		
				}
			}
		}
		addQueryWhere( usageLink , task );
		try {
			task.invoke();
		} catch (IEException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 判断数据库中是否存在该条数据
	 * @param usageLink
	 * @return
	 */
	private static boolean hasObject( WTPartUsageLink usageLink ) {
		boolean hasObject = false;
		
		Group group = query( usageLink );
		
		if( group != null && group.getElementCount() > 0 ){
			hasObject = true;
		}
		
		return hasObject;
	}
	
	/**
	 * 创建Task的where条件
	 * @param usageLink
	 * @param task
	 */
	private static void addQueryWhere( WTPartUsageLink usageLink, Task task ) {
		
		if( usageLink == null || task == null ){
			return;
		}
		
		String where = "parent_Number ='" + AttributeUtil.getAttribute( usageLink , "parentNumber") + "' " ;
		where = where + " And " + "parent_View='" + AttributeUtil.getAttribute(usageLink, "parentView") + "' " ;
		where = where + " And " + "parent_Major_Version='" + AttributeUtil.getAttribute(usageLink, "parentMajorVersion") + "' " ;
		where = where + " And " + "child_PartNumber='" + AttributeUtil.getAttribute(usageLink, "childNumber") + "' " ;
		
		task.addParam("WHERE", where);
	}
}
